import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { getUserInfoApi, getUserMenuListApi } from '../../services'
import type { UserInfo, MenuItem } from '../../types/services'

export const getUserInfoAction = createAsyncThunk('user/getUserInfo', async () => {
  try {
    const [userInfoRes, menuListRes] = await Promise.all([getUserInfoApi(), getUserMenuListApi()])
    return {
      userInfo: userInfoRes.data.data,
      siderMenuList: menuListRes.data.data.list
    }
  } catch(e) {
    return Promise.reject(e)
  }
})

interface State {
  userInfo: UserInfo | null
  siderMenuList: MenuItem[]
  userLoading: boolean
}

const initialState: State = {
  userInfo: null,
  siderMenuList: [],
  userLoading: false
}

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {},
  extraReducers: builder => {
    builder
    .addCase(getUserInfoAction.pending, (state) => {
      state.userLoading = true
    })
    .addCase(getUserInfoAction.fulfilled, (state, { payload }) => {
      state.userInfo = payload.userInfo
      state.siderMenuList = payload.siderMenuList
      state.userLoading = false
    })
    .addCase(getUserInfoAction.rejected, (state, payload) => {
      state.userLoading = false
    })
  }
})

export default userSlice.reducer